﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using Hangjing.Common;
using Newtonsoft.Json;
using System.Text;
using System.IO;
using Hangjing.Model;
using Hangjing.DBUtility;
using Hangjing.SQLServerDAL;
using System.Collections.Specialized;

using Hangjing.meituanapi;
using Hangjing.WebCommon;
using Hangjing.BaiduMapServerAPI;

/// <summary>
/// 商家已经确认，美团调用
/// </summary>
public partial class api_meituan_heartbeat_receiveorder : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Response.Clear();

        string order = Server.UrlDecode(Request["order"]);
        //Hangjing.AppLog.AppLog.Info("美团订单确认内容：" + order);
        apiResultInfo rs = new apiResultInfo();
        System.IO.Stream stream = Request.InputStream;//这是你获得的流
        if (stream != null && stream.Length > 10)
        {

            Hangjing.AppLog.AppLog.Info("stream.Length ：" + stream.Length);
            string jsondata = "";
            using (StreamReader reader = new StreamReader(stream))
            {
                jsondata = reader.ReadToEnd(); ;
            }

            Hangjing.AppLog.AppLog.Info("美团订单信息：" + jsondata);

        }
        else
        {
            rs.state = 0;
            rs.msg = "参数错误";
        }

        if (order.Length > 0)
        {
            mtorderInfo model = JsonConvert.DeserializeObject<mtorderInfo>(order);

            shopeleCustorder dal = new shopeleCustorder();

            CustorderInfo infos = new CustorderInfo();
            infos.orderid = "m" + model.orderId.ToString();

            if (dal.GetCount("orderid = '" + infos.orderid + "'") > 0)
            {
                Response.Write("{\"data\":\"OK\"}");
                return;
            }

            //1.加到系统，
            Custorder ordermodel = new Custorder();
            decimal allfoodmoney = 0;

            int qty = 0;
            PointsInfo togomodel = new Points().GetSendFeeModel(Convert.ToInt32(model.ePoiId));

            if (togomodel == null)
            {
                HJlog.toLog(" 美团商家（" + model.ePoiId + "）（" + model.poiName + "）未绑定");
                return;
            }


            IList<Hangjing.Model.ETogoShoppingCart> Foods = new List<Hangjing.Model.ETogoShoppingCart>();

            Hangjing.Model.ETogoShoppingCart myshopcart = new Hangjing.Model.ETogoShoppingCart();
            myshopcart.TogoId = togomodel.Unid;
            myshopcart.sendfree = 0;
            //满多少元免配送费未处理
            myshopcart.ItemList = null;

            IList<ETogoShoppingCartInfo> foodlist = new List<ETogoShoppingCartInfo>();

            IList<mtorderfoodInfo> mtfoods = JsonConvert.DeserializeObject<IList<mtorderfoodInfo>>(model.detail);


            foreach (var food in mtfoods)
            {
                ETogoShoppingCartInfo cartfood = new ETogoShoppingCartInfo();
                cartfood.PId = 0;
                cartfood.PName = food.food_name;
                cartfood.PNum = food.quantity;
                cartfood.PPrice = food.price;
                cartfood.Currentprice = cartfood.PPrice;
                cartfood.Foodcurrentprice = cartfood.PPrice;
                cartfood.Remark = "";
                cartfood.packagefee = food.box_num * food.box_price;


                allfoodmoney += cartfood.PPrice * cartfood.PNum;
                allfoodmoney += cartfood.packagefee * cartfood.PNum;

                qty += cartfood.PNum;

                foodlist.Add(cartfood);


            }
            myshopcart.ItemList = foodlist;
            Foods.Add(myshopcart);



            infos.OrderChecker = 10;
            infos.OrderAddress = model.poiName;

            infos.OrderRcver = model.recipientName;
            infos.OrderComm = model.recipientPhone;
            infos.OrderAttach = "";

            string Remark = model.caution;

            if (model.hasInvoiced == 1)
            {
                Remark += "[发票：" + model.invoiceTitle + "]";
            }
            Remark += "[美团" + model.daySeq + "号单]";

            infos.OrderAttach = Remark;

            infos.AddressText = model.recipientAddress;
            infos.SendTime = DateTime.Now.AddMinutes(50);
            if (model.deliveryTime != 0)
            {
                infos.SendTime = Utils.GetTime(model.deliveryTime.ToString());
            }


            infos.cityid = 0;
            infos.fromweb = ((int)OrderSource.api).ToString();
            infos.tempcode = "";
            infos.tempcode = "";
            infos.CustomerName = "";
            infos.ReveVar1 = togomodel.sentorg;



            infos.OldPrice = allfoodmoney;

            infos.OrderSums = model.total;


            infos.TogoId = togomodel.Unid;
            infos.P2Sign = "";
            infos.paytime = Convert.ToDateTime("1970-1-1");
            infos.paymode = 4;
            infos.ReveDate1 = DateTime.Now;

            infos.cardids = "";


            infos.settlecycle = togomodel.PType;
            infos.Advance = 0;
            infos.Mergeorderremark = "";
            infos.SystemUserId = 0;
            infos.IsShopSet = 0;
            infos.ReveDate1 = DateTime.Now;

            IList<Hangjing.Model.ETogoShoppingCart> list = Foods;

            string ulat = "0";
            string ulng = "0";

            //SendInfo send = new SendInfo();


            //string[] bdlatlng = Hangjing.Common.HjNetHelper.bd_encrypt(model.latitude, model.longitude);
            //ulat = bdlatlng[0];
            //ulng = bdlatlng[1];


            //调用百度接口转换坐标
            BaiduMap map = new BaiduMap(model.latitude.ToString(), model.longitude.ToString());
            string[] newbdlatlgn = map.getBaiDuLatLng();

            ulat = newbdlatlgn[0];
            ulng = newbdlatlgn[1];


            SendfeeInfo info = new SendfeeInfo();
            info.ShopID = togomodel.Unid;
            info.userpay = infos.OrderSums;
            info.latlng = new latlnginfo();
            info.latlng.ulat = ulat;
            info.latlng.ulng = ulng;

            SendFee fee = new SendFee(info);
            SendInfo senddata = fee.getSendFee();

            infos.Commission = WebHelper.getShopCommission(allfoodmoney, togomodel);
            infos.shopdiscountmoney = senddata.sendmoney;
            infos.cardpay = senddata.Distance;

            infos.ReveVar2 = "{'ulat':'" + ulat + "','ulng':'" + ulng + "','slat':'" + togomodel.Lat + "','slng':'" + togomodel.Lng + "'}";

            foreach (Hangjing.Model.ETogoShoppingCart item in Foods)
            {
                item.latlng = infos.ReveVar2;
            }

            if (model.payType == 2)
            {
                infos.paystate = 1;
                infos.paymoney = model.total;
                infos.paymode = 1;
                infos.paytime = DateTime.Now;

            }

            ////这里进行所有的判断
            IList<ROrderinfo> mylist = dal.SubmitOrder(Foods, infos);

            if (mylist != null)
            {
                if (infos.paystate == 1)
                {
                    dal.UpdatePayState(infos);
                }

                WebUtility.excutesql("UPDATE dbo.shopeleCustorder SET systemuserid = 1 WHERE orderid = '" + infos.orderid + "'");
                if (togomodel.PosSrvAd.Trim() == "1")//自动导入正式系统
                {
                    WebHelper.sendMTOrder2system(infos.orderid);
                }

                Response.Write("{\"data\":\"OK\"}");

            }
            else
            {
                Response.Write("{\"data\":\"error\"}");
            }

        }



        Response.End();

    }
}